package org.diysearch.helpers;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.diysearch.dao.interfaces.PageDao;
import org.diysearch.models.Page;
import org.diysearch.models.PageElement;
import org.diysearch.tools.BaseTool;

public abstract class PageHelper {
	private static final Log LOG = LogFactory.getLog(PageHelper.class);
	private static final PageDao dao = (PageDao) BaseTool.IOC_ENGINE.getBean("pageDao");
	
	public static Page getPage(String uri) throws Exception {
		return getPage(uri,1);
	}
	public static Page getPage(String uri, int isPublished) throws Exception {
		Page p = new Page();
		p.setUri(uri);
		p.setIsPublished(isPublished);
		return dao.findByUri(p);
	}
	
	public static List<Page> getUnpublishedPages() throws Exception {
		return dao.findByUnpublished();
	}
	
	public static List<Page> getPublishedPages() throws Exception {
		return dao.findByPublished();
	}
	
	public static int publishPage(String uri) throws Exception {
		Page p = new Page();
		p.setUri(uri);
		p.setIsPublished(1);
		return dao.setPublish(p);
	}
	
	public static int unpublishPage (String uri) throws Exception {
		Page p = new Page();
		p.setUri(uri);
		p.setIsPublished(0);
		return dao.setPublish(p);
	}
	
	public static int markAsPublishable (String uri) throws Exception {
		Page p = new Page();
		p.setUri(uri);
		p.setDoNotPublish(0);
		return dao.setPublishable(p);
	}
	
	public static int markAsUnPublishable (String  uri) throws Exception {
		Page p = new Page();
		p.setUri(uri);
		p.setDoNotPublish(0);
		return dao.setPublishable(p);
	}
	
	public static int save(
			int id,
			String uri,
			String title,
			int isPublished,
			int doNotPublish,
			int isPage,
			String author,
			String template,
			List<Map<String,String>> elements) throws Exception
	{
		Page p = new Page();
		p.setId(id);
		p.setAuthor(author);
		p.setDoNotPublish(doNotPublish);
		p.setIsPage(isPage);
		p.setIsPublished(isPublished);
		p.setTemplate(template);
		p.setUri(uri);
		p.setTitle(title);
		
		for (Map<String,String> element : elements) {
			for (String key : element.keySet()) {
				PageElement pe = new PageElement();
				pe.setKey(key);
				pe.setValue(element.get(key));
				p.addPageElement(pe);
			}
		}
		
		return dao.save(p);
	}
}
